package com.bj.dljd.excepyions.hands;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bj.dljd.excepyions.BossException;
import com.bj.dljd.models.response.R;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler({ BossException.class})
    public R doBossException(BossException bossException){
        logger.error("Boss项目异常，code:{},原因:{}",bossException.getRespCode().getCode(),
                bossException.getRespCode().getMsg());
        return BossException.WARN(bossException.getRespCode());
    }

    @ExceptionHandler({BindException.class})
    public R doBeanValidation(BindException bindException){
        logger.error("Boss项目异常：控制器防范参数验证失败{}:" + bindException.getNestedPath());
        List<FieldError> fieldErrors = bindException.getFieldErrors();
        JSONArray array = new JSONArray();
        StringBuilder builder = new StringBuilder();
        fieldErrors.forEach(fieldError->{
//            builder.append(fieldError.getField()).append("错误提示:").append(fieldError.getDefaultMessage());
            JSONObject entries = new JSONObject();
            entries.set(fieldError.getField(),fieldError.getDefaultMessage());
            array.add(entries);
        });
        return R.builder().code(301).msg("请求参数异常").data(array).build();
    }

}
